package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video-management-system/cache"
	"video-management-system/model"
	"video-management-system/pkg"

	"video-management-system/userrpc/internal/svc"
	"video-management-system/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *RegisterLogic) Register(in *userrpc.RegisterRequest) (*userrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var findUser model.User
	err := findUser.FindUserByPhone(model.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	if findUser.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}
	result, _ := cache.Rdb.Get(l.ctx, "sms"+in.Phone).Result()
	if result == "" {
		return nil, errors.New("请发送验证码")
	}
	if result != in.SandCode {
		return nil, errors.New("验证码错误")
	}

	user := model.User{
		PhoneNum:   in.Phone,
		Password:   pkg.Str(in.Password),
		Nickname:   fmt.Sprintf("游客%v", rand.Intn(9000)),
		AvatarLink: "http://t4kaai1ut.hn-bkt.clouddn.com",
	}

	if err = user.UserAdd(model.DB); err != nil {
		return nil, errors.New("注册失败")
	}
	return &userrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
